package com.yunqian.web;

import com.yunqian.exception.ActionException;
import com.yunqian.redot.constant.ConstantKey;
import com.yunqian.redot.domain.Customers;
import com.yunqian.redot.service.CustomersService;
import com.yunqian.util.validate.Validator;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author czy
 * @describe
 * @date 2018/7/6
 */
@RestController
@RequestMapping("/api/token")
public class TokenController {

    @Autowired
    private CustomersService customersService;

    /**
     * 嗅探Token是否过期 未过期-200 过期-401
     *
     * @return
     */
    @GetMapping("/sniffer")
    public Object tokenAuth() {
        return null;
    }

    /**
     * 重新获取Token
     *
     * @param customers
     * @param res
     * @return
     */
    @PostMapping("/refresh")
    public Customers tokenRefresh(@RequestBody Customers customers, HttpServletResponse res) {

        if (Validator.isNull(customers.getOpenId()) || Validator.isNull(customers.getPhone())) {
            throw new ActionException("openId和phone不能为空");
        }
        Customers cus = customersService.getByPhoneAndOpenId(customers.getPhone(),customers.getOpenId());
        if (Validator.isNull(cus)) {
            throw new ActionException("校验失败，该用户不存在");
        }
        String token = Jwts.builder()
                .setSubject(cus.getPhone())
                .setExpiration(new Date(System.currentTimeMillis() + ConstantKey.TOKEN_EXPIRATION_WECHAT))
                .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                .compact();
        res.addHeader("Authorization", "Bearer " + token);
        return cus;
    }
}
